Advertisement
xeritt

Сортировка массива указателей на структуры через qsort

Nov 10th, 2016
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. /*
  2.   gcc -std=c99 -Wall -o "input" "input.c"
  3.   ./input < test.txt
  4.  
  5. test.txt
  6. 3
  7. Петр
  8. Иванов
  9. 14
  10. Иван
  11. Петров
  12. 34
  13. Алена
  14. Смирнова
  15. 44
  16.  
  17.  */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. struct stud{
  21.     char name[50];
  22.     char fname[50];
  23.     int balls;
  24. };
  25. typedef struct stud st;
  26.  
  27. void readStudent(st* student){
  28.     printf("Введите Имя:");
  29.     scanf("%s", student->name);
  30.     printf("Введите Фамилию:");
  31.     scanf("%s", student->fname);
  32.     printf("Введите баллы:");
  33.     scanf("%d", &student->balls);
  34. }
  35. void readStudents(st** student, int count){
  36.     for (int i = 0; i < count ; i++){
  37.         student[i] = (st*) malloc (sizeof(st));
  38.         readStudent(student[i]);
  39.     }
  40. }
  41.  
  42. void printStudents(st** student, int count){
  43.     for (int i = 0; i < count ; i++){
  44.         printf("Имя:");
  45.         printf("%s\n", student[i]->name);
  46.         printf("Фамилия:");
  47.         printf("%s\n", student[i]->fname);
  48.         printf("баллы:");
  49.         printf("%d\n", student[i]->balls);
  50.     }
  51. }
  52.  
  53. static int cmp(const void *p1, const void *p2){
  54.     st * st1 = *(st**)p1;
  55.     st * st2 = *(st**)p2;
  56.     return st2->balls - st1->balls;
  57. }
  58.  
  59. int main(int argc, char **argv){
  60.     int count = 3;
  61.     printf("Введите кол-во:");
  62.     scanf("%d", &count);
  63.     st** mas = (st**)malloc(sizeof(st**)*count);
  64.     readStudents(mas, count);
  65.     qsort(mas, count, sizeof(st*), cmp);
  66.     printStudents(mas, count);
  67.    
  68.     for (int i = 0; i < count; i++)
  69.     {
  70.         free(mas[i]);
  71.     }
  72.     free(mas);
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement